<template>
  <div class="user-table-container">
    <el-button size="mini" type="primary" @click="handleadd()">
      新增
    </el-button>
    <el-table ref="tableRef" :data="result.users" tooltip-effect="dark"
      style="width: 100%; max-width: 1000px; margin: 0 auto;" border highlight-current-row>
      <el-table-column type="selection" width="40"></el-table-column>
      <el-table-column label="ID" width="80" sortable>
        <template #default="scope">{{ scope.row.id }}</template>
      </el-table-column>
      <el-table-column label="用户名" width="80">
        <template #default="scope">{{ scope.row.username }}</template>
      </el-table-column>
      <el-table-column label="真实姓名" width="80">
        <template #default="scope">{{ scope.row.realName }}</template>
      </el-table-column>
      <el-table-column label="昵称" width="80">
        <template #default="scope">{{ scope.row.nickName }}</template>
      </el-table-column>
      <el-table-column label="角色" width="100">
        <template #default="scope">
          <el-tag :type="getRoleType(scope.row.roleName)">{{ scope.row.roleName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="性别" width="80">
        <template #default="scope">
          <span v-if="scope.row.gender === 1">男</span>
          <span v-else-if="scope.row.gender === 0">女</span>
          <span v-else>未知</span>
        </template>
      </el-table-column>
      <el-table-column label="手机" width="89">
        <template #default="scope">{{ scope.row.phone }}</template>
      </el-table-column>
      <el-table-column label="邮箱" width="90">
        <template #default="scope">{{ scope.row.email }}</template>
      </el-table-column>
      <el-table-column label="操作" width="280">
        <template #default="scope">
          <div class="flex justify-center space-x-1">
            <el-button size="mini" type="primary" class="btn-edit smaller-btn"
              @click="handleEdit(scope.$index, scope.row)">
              <i class="el-icon-edit"></i> <span class="btn-text">编辑</span>
            </el-button>
            <el-button size="mini" type="warning" class="btn-assign smaller-btn"
              @click="handleAssignRole(scope.$index, scope.row)">
              <i class="el-icon-s-custom"></i> <span class="btn-text">分配角色</span>
            </el-button>
            <el-button size="mini" type="danger" class="btn-delete smaller-btn"
              @click="handleDelete(scope.$index, scope.row)">
              <i class="el-icon-delete"></i> <span class="btn-text">删除</span>
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页控件 -->
    <div class="pagination-container mt-4 flex justify-between items-center">
      <div class="text-sm text-gray-500">
        共 {{ result.totalSize }} 条记录
      </div>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page.pageNo"
        :page-sizes="[5, 10, 20, 50]" :page-size="page.pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="result.totalSize">
      </el-pagination>
    </div>
    <Useraddedit ref="useraddedit" :addVisible="addVisible" :title="title" @closeDialog="closeDialog"></Useraddedit>
    <AssignRole ref="assignRole" :roleVisible="roleVisible" @closeDialog="closeDialog"></AssignRole>
  </div>

</template>

<script>
import { usePageApi, delUseApi } from '@/api/UseApi';
import Useraddedit from '@/components/user/Useraddedit.vue';
import AssignRole from '@/components/user/AssignRole.vue';

export default {
  data() {
    return {
      page: {
        pageNo: 1,
        pageSize: 5,
      },
      result: {
        users: [],
        totalPage: 1,
        totalSize: 0
      },
      addVisible: false,
      roleVisible: false,
      title: ''
    }
  },
  components: {
    Useraddedit,
    AssignRole
  },
  mounted() {
    this.lodeUses();
  },
  methods: {
    async lodeUses() {
      try {
        const res = await usePageApi(this.page);
        if (res.status === 200) {
          this.result.users = res.data.records;
          this.result.totalPage = res.data.pages;
          this.result.totalSize = res.data.total;
        } else {
          this.$message.error(res.msg);
        }
      } catch (error) {
        console.error('获取用户列表失败:', error);
        this.$message.error('网络错误，请稍后重试');
      }
    },

    // 分页相关方法
    handleSizeChange(newSize) {
      this.page.pageSize = newSize;
      this.lodeUses();
    },

    handleCurrentChange(newPage) {
      this.page.pageNo = newPage;
      this.lodeUses();
    },

    // 获取角色标签样式
    getRoleType(roleName) {
      const roles = {
        '管理员': 'danger',
        '编辑': 'warning',
        '普通用户': 'info',
        '访客': 'success'
      };
      return roles[roleName] || 'primary';
    },

    // 操作方法
    closeDialog(isReflush = false) {
      this.addVisible = false;
      this.roleVisible = false;
      isReflush && this.lodeUses();
    },
    handleadd() {
      this.addVisible = true;
      this.title = '新增用户';
      this.$refs.useraddedit.openDialog();

    },
    handleEdit(index, row) {
      console.log('编辑用户:', row);
      this.addVisible = true;
      this.title = '编辑用户';
      this.$refs.useraddedit.openDialog(row.id);

    },

    handleAssignRole(index, row) {
      this.roleVisible = true;
      this.$refs.assignRole.openDialog(row.id);

    },

    handleDelete(index, row) {
      this.$confirm('确定要删除此用户吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await delUseApi(row.id);
          if (res.status === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });

          } else {
            this.$message.error(res.msg);
          }
        } catch (error) {
          console.error('获取用户列表失败:', error);
          this.$message.error('网络错误，请稍后重试');
        }


        this.lodeUses(); // 刷新数据
      }).catch(() => {
        // 取消操作
      });
    }
  }
}
</script>

<style scoped lang="less">
.user-table-container {
  // 表格容器样式

  .pagination-container {
    // 分页容器样式
    padding: 10px;
    background-color: #f5f7fa;
    border-radius: 0 0 4px 4px;
  }

  // 优化表格样式
  .el-table {
    &__header th {
      background-color: #f5f7fa;
      color: #606266;
      font-weight: 600;
    }

    &__row {
      transition: all 0.2s ease;

      &:hover {
        background-color: #fafbfc !important;
      }
    }

    // 隐藏水平滚动条
    &__body-wrapper {
      overflow-x: hidden;
    }
  }

  // 按钮样式优化
  .btn-edit {
    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);
    }
  }

  .btn-assign {
    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);
    }
  }

  .btn-delete {
    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);
    }
  }

  // 按钮组样式
  .flex {
    display: flex;
  }

  .justify-center {
    justify-content: center;
  }

  .space-x-1 {
    gap: 4px;
  }

  // 新增按钮变小样式
  .smaller-btn {
    padding: 2px 4px;
    font-size: 10px;
  }

  // 调整按钮文字样式，进一步缩小字体
  .btn-text {
    font-size: 9px;
  }
}
</style>